#!/usr/bin/python3

"""
target-pool
Author: David Chang
Last revision: Feb 26th, 2019
"""

import random
import os.path
import utils

random.seed()

target_pool = os.path.expanduser("~/.target_pool")

if not os.path.exists(target_pool):
    with open(target_pool,"w") as f:
        f.write("# target\tweight\n")

with open(target_pool) as f:
    target_lines = [line.strip() for line in f.readlines() if not line.startswith("#")]
    target_lines = [line if "#" not in line else line[0:line.find("#")].strip() for line in target_lines]
    target_lines = [line for line in target_lines if len(line)!=0]
targets = []
sum_weight = 0
for line in target_lines:
    target,weight = utils.splitline(line)
    targets.append((target,weight))
    sum_weight += weight

seq = random.randrange(0,sum_weight)
sum_weight = 0
for item in targets:
    sum_weight += item[1]
    if sum_weight>seq:
        print("Seq#: {:d}\tTarget: {:}\tWeight: {:d}".format(
                    seq+1,item[0],item[1]))
        break
